package com.ruoyi.framework.web.service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.aliyun.SendMessage;
import com.ruoyi.framework.security.UsernamePhoneAuthenticationToken;
import com.ruoyi.system.domain.dto.CaptchaDTO;
import com.ruoyi.system.domain.dto.CaptchaLoginDTO;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    private final String SMS_CODE ="sms_code:";

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());



    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public AjaxResult sendCaptcha(CaptchaDTO captcha, HttpServletRequest request) {
        boolean mobileNO = VerifyUtils.isMobileNO(captcha.getPhone());
        if (mobileNO) {
            try {
                String ipAddr = IpUtils.getIpAddr(request);
                String key = SMS_CODE + ipAddr;
                //获取该Ip发送验证码的次数
                Integer num = redisCache.getCacheObject(key);
                if (num == null) {
                    num = 1;
                    redisCache.setCacheObject(key, num, 1, TimeUnit.MINUTES);
                } else {
                    return AjaxResult.error("发送短信过于频繁，请稍后在试！");
                }

                // 生成随机6位数验证码
                int verifyCode = VerifyCodeUtils.getCaptcha();
                String verifyKey = CaptchaDTO.codeType(captcha.getCodeType(), captcha.getPhone());
                //先查询缓存中是否有发过的验证码
                Integer code = redisCache.getCacheObject(verifyKey);
                if (StringUtils.isNotNull(code)) {
                    //验证码未消费，发回相同的验证码给回用户
                    verifyCode = code;
                }
                //发送短信
                if (!SendMessage.sendSms(captcha.getPhone(), verifyCode)) {
                    return AjaxResult.error("验证码请求已超过每日最大数量，请明天再试！");
                }

                //存入redis
                redisCache.setCacheObject(verifyKey, verifyCode, 10, TimeUnit.MINUTES);
                return AjaxResult.success("验证码发送成功！");
            } catch (Exception e) {
                logger.error("获取手机登录验证码：手机号:{}获取验证码失败！错误信息{}", captcha.getPhone(), e.getMessage());
                return AjaxResult.error("手机号错误，请重新输入！");
            }
        }
        return AjaxResult.error("手机号错误，请重新输入！");
    }

    @Transactional
    public AjaxResult captchaLogin(CaptchaLoginDTO dto) {
        //校验手机号
        if (VerifyUtils.isMobileNO(dto.getUserName())) {
            //判断验证码是否正确
            String verifyKey = CaptchaDTO.codeType(dto.getCodeType(), dto.getUserName());
            //先查询缓存中是否有发过的验证码
            Integer code = redisCache.getCacheObject(verifyKey);
            if (StringUtils.isEmpty(verifyKey)) {
                //验证码过期或者失效
                logger.error("获取验证码登录失败，用户手机号：{}，失败原因：验证码过期或者失效！", dto.getUserName());
                return AjaxResult.error("短信验证码过期或者失效");
            }
            if (!dto.getCode().equals(code)) {
                //验证码错误
                logger.error("获取验证码失败，用户手机号：{}，失败原因：验证码错误！", dto.getUserName());
                return AjaxResult.error("短信验证码错误");
            } else {
                //判断用户类型
                SysUser user = userService.selectUserByPhonenumber(dto.getUserName());
                if(ObjectUtils.isEmpty(user)){
                    return AjaxResult.error("没有查询到手机号"+dto.getUserName()+"对应的用户");
                }
                //删除验证码缓存
                redisCache.deleteObject(verifyKey);
                if (!"0".equals(user.getStatus())) {
                    return AjaxResult.error("该账号已被停用");
                }
                if ("2".equals(user.getDelFlag())){
                    return AjaxResult.error("该账号已被删除");
                }

                String phonenumber = user.getPhonenumber();
                String userName = user.getUserName();


                // 用户验证
                Authentication authentication = null;
                try
                {
                    // 该方法会去调用UsernamePhoneUserDetailsServiceImpl.loadUserByUsername
                    authentication = authenticationManager.authenticate(new UsernamePhoneAuthenticationToken(phonenumber));

                }
                catch (Exception e)
                {
                    if (e instanceof BadCredentialsException)
                    {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                        throw new UserPasswordNotMatchException();
                    }
                    else
                    {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_FAIL, e.getMessage()));
                        throw new ServiceException(e.getMessage());
                    }
                }
                finally
                {
                    AuthenticationContextHolder.clearContext();
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                recordLoginInfo(loginUser.getUserId());
                // 生成token
                String token = tokenService.createToken(loginUser);
                return AjaxResult.success("token",token);
            }
        }
        return AjaxResult.error("请检查手机号是否正确");
    }


    public AjaxResult resetPassword(CaptchaLoginDTO dto) {
        //校验手机号
        if (VerifyUtils.isMobileNO(dto.getUserName())) {
            //判断验证码是否正确
            String verifyKey = CaptchaDTO.codeType(dto.getCodeType(), dto.getUserName());
            //先查询缓存中是否有发过的验证码
            Integer code = redisCache.getCacheObject(verifyKey);
            if (StringUtils.isEmpty(verifyKey)) {
                //验证码过期或者失效
                logger.error("获取验证码登录失败，用户手机号：{}，失败原因：验证码过期或者失效！", dto.getUserName());
                return AjaxResult.error("短信验证码过期或者失效");
            }
            if (!dto.getCode().equals(code)) {
                //验证码错误
                logger.error("获取验证码失败，用户手机号：{}，失败原因：验证码错误！", dto.getUserName());
                return AjaxResult.error("短信验证码错误");
            } else {
                //判断用户类型
                SysUser user = userService.selectUserByPhonenumber(dto.getUserName());
                if(ObjectUtils.isEmpty(user)){
                    return AjaxResult.error("用户名错误");
                }
                if (!"0".equals(user.getStatus())) {
                    return AjaxResult.error("该账号已被停用");
                }
                if ("2".equals(user.getDelFlag())){
                    return AjaxResult.error("该账号已被删除");
                }
                String newPassword = dto.getNewPassword();
                String reNewPassword = dto.getReNewPassword();
                if(!StringUtils.equals(newPassword,reNewPassword)){
                    return AjaxResult.error("密码输入错误，请重新输入");
                }
                SysUser sysUser = new SysUser();
                sysUser.setUserId(user.getUserId());
                sysUser.setPassword(newPassword);
                userService.updateUserProfile(sysUser);
                //删除验证码缓存
                redisCache.deleteObject(verifyKey);
                return AjaxResult.success("密码重置成功");
            }
        }
        return AjaxResult.error("请检查手机号是否正确");
    }


    public AjaxResult checkCerificationCode(CaptchaLoginDTO dto){
        //校验手机号
        if (VerifyUtils.isMobileNO(dto.getUserName())) {
            //判断验证码是否正确
            String verifyKey = CaptchaDTO.codeType(dto.getCodeType(), dto.getUserName());
            //先查询缓存中是否有发过的验证码
            Integer code = redisCache.getCacheObject(verifyKey);
            if (StringUtils.isEmpty(verifyKey)) {
                //验证码过期或者失效
                logger.error("获取验证码登录失败，用户手机号：{}，失败原因：验证码过期或者失效！", dto.getUserName());
                return AjaxResult.error("短信验证码过期或者失效");
            }
            if (!dto.getCode().equals(code)) {
                //验证码错误
                logger.error("获取验证码失败，用户手机号：{}，失败原因：验证码错误！", dto.getUserName());
                return AjaxResult.error("短信验证码错误");
            }
        }
        return AjaxResult.success("验证码正确");
    }
}
